﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using HeritageAcademy.Models.DataModels;
using WinForms = Microsoft.Win32;

namespace HeritageAcademy.Library.Controls
{
    /// <summary>
    /// Interaction logic for OptionsView.xaml
    /// </summary>
    public sealed partial class Registration
    {
        #region Parameters

        private readonly Image _anonimousImage;

        #endregion

        #region Ctor

        public Registration()
        {
            InitializeComponent();
            imgAvatar.MouseLeftButtonDown += imgAvatar_MouseLeftButtonDown;

            // Anonimous image
            _anonimousImage = new Image();
        }

        #endregion

        #region Methods

        /// <summary>
        ///   Locates and returns the path to the "Content\" folder
        ///   containing the fixed document for the sample.</summary>
        /// <returns>
        ///   The path to the fixed document "Content\" folder.
        /// </returns>
        public string GetContentFolder()
        {
            // Get the path to the current directory and its length.
            var contentDir = Directory.GetCurrentDirectory();
            var dirLength = contentDir.Length;

            // If we're in "...\bin\debug", move up to the root.
            if (contentDir.ToLower().EndsWith(@"\bin\debug"))
                contentDir = contentDir.Remove(dirLength - 10, 10);
                // If we're in "...\bin\release", move up to the root.
            else if (contentDir.ToLower().EndsWith(@"\bin\release"))
                contentDir = contentDir.Remove(dirLength - 12, 12);

            // If there's a "Content" subfolder, that's what we want.
            if (Directory.Exists(contentDir + @"\Content"))
                contentDir = contentDir + @"\Content";

            // Return the "Content\" folder (or the "current"
            // directory if we're executing somewhere else).
            return contentDir;
        }

        /// <summary>
        /// Clear all inputs in registration form.
        /// </summary>
        public void Clear()
        {
            IsOpen = false;
            tbLogin.Text = string.Empty;
            tbName.Text = string.Empty;
            tbFamilyName.Text = string.Empty;
            tbRole.Text = string.Empty;
            tbPassword.Password = string.Empty;
            tbPasswordConfirmation.Password = string.Empty;
            if (_anonimousImage.Source != null) imgAvatar.Source = _anonimousImage.Source;
        }

        /// <summary>
        /// Create new user object using form input data.
        /// </summary>
        /// <returns></returns>
        public User NewUser()
        {
            var u = new User();
            if (tbPassword.Password == tbPasswordConfirmation.Password)
            {
                // Add new user to users data object and save all to database
                u.Id = Guid.NewGuid().ToString();
                u.Login = tbLogin.Text;
                u.Name = tbName.Text;
                u.FamilyName = tbFamilyName.Text;
                u.Role = tbRole.Text;
                u.Password = tbPassword.Password;
                if (!Equals(imgAvatar.Source, "")) u.Icon = imgAvatar.Source.ToString();
            }
            else
            {
                // Reaction on passwords does't match situation
                MessageBox.Show("Пароли не совпадают!"); // TODO: Implement something not so brut
                tbPassword.Password = "";
                tbPasswordConfirmation.Password = "";
                tbPassword.Focus();
            }
            return u;
        }

        #endregion

        #region Event Handlers

        private void imgAvatar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var dialog = new WinForms.OpenFileDialog
                             {
                                 Title = "Вставить аватар",
                                 InitialDirectory = GetContentFolder(),
                                 CheckFileExists = true,
                                 Filter = "Изображения (*.png,*.jpg,*.jpeg,*.bmp)|" +
                                          "*.png;*.jpg;*.jpeg;*.bmp|All (*.*)|*.*"
                             };
            dialog.ShowDialog();


            if (dialog.FileName == "") return;
            var bimg = new BitmapImage();
            bimg.BeginInit();
            bimg.UriSource = new Uri(dialog.FileName);
            bimg.EndInit();

            _anonimousImage.Source = imgAvatar.Source;
            imgAvatar.Source = bimg;
        }

        /// <summary>
        /// Register button routed event handler.
        /// </summary>
        public RoutedEventHandler RegistrationButtonEventHandler
        {
            set { btnRegister.Click += value; }
        }

        #region IsOpen

        /// <summary>
        /// IsOpen Dependency Property
        /// </summary>
        private static readonly DependencyProperty IsOpenProperty =
            DependencyProperty.Register("IsOpen", typeof (bool), typeof (Registration),
                                        new FrameworkPropertyMetadata(false,
                                                                      new PropertyChangedCallback(OnIsOpenChanged)));

        /// <summary>
        /// Gets or sets the IsOpen property.  This dependency property 
        /// indicates ....
        /// </summary>
        public bool IsOpen
        {
            get { return (bool) GetValue(IsOpenProperty); }
            private set { SetValue(IsOpenProperty, value); }
        }

        /// <summary>
        /// Handles changes to the IsOpen property.
        /// </summary>
        private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((Registration) d).OnIsOpenChanged(e);
        }

        /// <summary>
        /// Provides derived classes an opportunity to handle changes to the IsOpen property.
        /// </summary>
        private void OnIsOpenChanged(DependencyPropertyChangedEventArgs e)
        {
            if ((bool) e.NewValue)
            {
                Visibility = Visibility.Visible;
                var open = Resources["Open"] as Storyboard;
                if (open != null) open.Begin(this);
            }
            else
            {
                Visibility = Visibility.Visible;
                var close = Resources["Close"] as Storyboard;

                EventHandler handler = null;
                handler = (object s, EventArgs sbe) =>
                              {
                                  if (close != null) close.Completed -= handler;
                                  Visibility = Visibility.Collapsed;
                              };

                if (close != null)
                {
                    close.Completed += handler;
                    close.Begin(this);
                }
            }
        }

        #endregion

        private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Clear();
        }

        #endregion
    }
}